package dbrpc

import (
	"bytes"
	"database/sql"
	"dub/define/grpcmodel"
	"dub/utils"
	"golang.org/x/net/context"
)

//与用户有关的数据库操作
type DbRpcUser struct {
	log *utils.Logger
}

//根据用户查询用户表的信息
func (u *DbRpcUser) FindUser(ctx context.Context, req *grpcmodel.ModelDbRpcUserReqFind) (reply *grpcmodel.ModelDbRpcUserResFindUser, err error) {
	reply = &grpcmodel.ModelDbRpcUserResFindUser{}
	dbAccounts := NewDbProxy().Get(DB_Accounts)
	sql_str := bytes.Buffer{}
	params := make([]interface{}, 0)
	sql_str.WriteString("select userId,userName,loginName,loginPwd,userStatus,UNIX_TIMESTAMP(userAddTime),userAddId from dubuser where 1=1")

	if req.GetLoginName() != "" {
		sql_str.WriteString(" and loginName=?")
		params = append(params, req.GetLoginName())
	}

	sql_str.WriteString(" limit 1")
	u.log.Infof("def_func_db_user.go FindUser method exec %s params is %+v\n", sql_str.String(), params)
	row := dbAccounts.QueryRow(sql_str.String(), params...)

	var (
		userId, userAddId, userStatus, userAddTime sql.NullInt64
		UserName, rowloginName, loginPwd           sql.NullString
	)
	err = row.Scan(&userId, &rowloginName, &rowloginName, &loginPwd, &userStatus, &userAddTime, &userAddId)

	switch {
	case err == sql.ErrNoRows:
		err = nil
		reply.Err = 1
	case err != nil:
		reply.Err = 2
		u.log.Errorf("def_fun_db_user.go FindUser method row.Scan err. %v\n", err)
	default:
		model := &grpcmodel.ModelDbRpcUser{}
		if userId.Valid {
			model.UserId = uint32(userId.Int64)
		}
		if userAddId.Valid {
			model.UserAddId = uint32(userAddId.Int64)
		}
		if userStatus.Valid {
			model.UserStatus = uint32(userStatus.Int64)
		}
		if UserName.Valid {
			model.UserName = UserName.String
		}
		if rowloginName.Valid {
			model.LoginName = rowloginName.String
		}
		if loginPwd.Valid {
			model.LoginPwd = loginPwd.String
		}

		if userAddTime.Valid {
			model.UserAddTime = uint64(userAddTime.Int64)
		}
		reply.ModelDbRpcUser = model
	}
	return
}

var d_dbRpcUser *DbRpcUser

func NewDbRpcUser() *DbRpcUser {
	if d_dbRpcUser == nil {
		d_dbRpcUser = &DbRpcUser{
			log: utils.NewLogger(),
		}
	}
	return d_dbRpcUser
}
